<?php
	#-------------------------------------------------------------#
	# This file is part of the Kumomado - Virtual Window Platform #
	# for PHP. (c) 2009 Tsai, Min Che <tirme0812@gmail.com>       #
	# Please visit http://www.kumomado.org/ for more information. #
	#                                                             #
	# This software is licensed under the GNU License v3. Please  #
	# view the LICENSE file for the full text of this license.    #
    #-------------------------------------------------------------#

	Kumomado::load('Criteria.KumomadoCriteriaElement');
	/**
	 * A single criteria
	 * @package libraries
	 * @subpackage criteria
	 * @author Tsai, Min Che
	 */
	class KumomadoCriteria extends KumomadoCriteriaElement {
		/**
		 * @var string
		 */
		private $prefix;
		/**
		 * @var string
		 */
		private $function;
		/**
		 * @var string
		 */
		private $column;
		/**
		 * @var string
		 */
		private $operator;
		/**
		 * @var string
		 */
		private $value;
		/**
		 * Construce
		 * @param string $column
		 * @param string $value[optional]
		 * @param string $operator[optional]
		 * @param string $prefix[optional]
		 * @param string $function[optional]
		 */
		public function __construct($column, $value = '', $operator = '=', $prefix = '', $function = '') {
			$this->prefix = $prefix;
			$this->function = $function;
			$this->column = $column;
			$this->value = $value;
			$this->operator = $operator;
		}
		/**
		 * Make a sql condition string
		 * @return string
		 */
		public function render() {
			$clause = (!empty($this->prefix) ? sprintf('`%s`.', $this->prefix) : '').sprintf('`%s`', $this->column);
			if (!empty($this->function)) {
				$clause = sprintf($this->function, $clause);
			}
			if (in_array(strtoupper($this->operator), array( 'IS NULL', 'IS NOT NULL'))) {
				$clause .= ' '.$this->operator;
			} else {
				if ('' === ($value = trim($this->value))) {
					return '';
				}
				if (!in_array(strtoupper($this->operator), array('IN', 'NOT IN'))) {
					if ((substr($value, 0, 1) != '`') && (substr($value, -1) != '`')) {
						$value = "'$value'";
					} elseif (!preg_match('/^[a-zA-Z0-9_\.\-`]*$/', $value)) {
						$value = '``';
					}
				}
				$clause .= sprintf('%s%s', $this->operator, $value);
			}
			return $clause;
		}
		/**
		 * Make a SQL "WHERE" clause
		 * @return string
		 */
		public function renderWhere() {
			$cond = $this->render();
			return empty($cond) ? '' : 'WHERE '.$cond;
		}
	}
?>